package com.leyou.item.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.vo.BrandVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 品牌表，一个品牌下有多个商品（spu），一对多关系 服务实现类
 * </p>
 *
 * @author guoxi
 * @since 2020-12-06
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private CategoryBrandService categoryBrandService;


    // 分页查询品牌
    @Override
    public PageDTO queryPage(Integer page, Integer rows, String key) {
        //泛型是品牌
        IPage<Brand> brandPage = new Page<>(page, rows);
//        //判断是否存在条件查询
//        boolean isBlank = StringUtils.isNotBlank(key);
//        QueryWrapper<Brand> brandQueryWrapper = null;
//        if (isBlank) {
//            //构建条件分页查询
//            brandQueryWrapper = new QueryWrapper<>();
//            brandQueryWrapper
//                    .like("name", key)
//                    .or()
//                    .eq("letter", key);
//        }

        //构建条件分页查询
        QueryWrapper<Brand> brandQueryWrapper = new QueryWrapper<>();
        brandQueryWrapper
                .like(key!=null,"name", key)
                .or()
                .eq(key!=null,"letter", key);


        page(brandPage, brandQueryWrapper);

        //分页记录列表Brand需要转化为BrandDTO
        return new PageDTO(brandPage.getTotal(),
                brandPage.getPages(),
                BrandDTO.convertEntityList(brandPage.getRecords()));
    }


    //根据id查询品牌
    @Override
    public BrandDTO queryBrandById(Long id) {
        return new BrandDTO(this.getById(id));
    }


    //根据品牌id集合查询品牌集合
    @Override
    public List<BrandDTO> queryBrandsByIds(List<Long> ids) {
        List<Brand> brands = listByIds(ids);
        return BrandDTO.convertEntityList(brands);
    }


    //根据分类id查询品牌
    @Override
    public List<BrandDTO> queryBrandsByCategoryId(Long cid) {

        List<Long> brandIds = categoryBrandService
                .query()
                .eq("category_id", cid)
                .list()
                .stream()
                .map(CategoryBrand::getBrandId)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(brandIds)) {
            throw new LyException("当前分类下没有品牌", 204);
        }

        List<BrandDTO> brandDTOList = queryBrandsByIds(brandIds);

        return brandDTOList;
    }

    //新增品牌
    @Override
    //开启本地事务
    @Transactional
    public void addBrand(BrandVo brandVo) {
        //将vo对象转换pojo数据库对象
        Brand brand = brandVo.toEntity(Brand.class);
        //保存品牌
        save(brand);

        //获取商品id集合
        List<Long> categoryIdList = brandVo.getCategoryIds();
        //获取分类id集合
        Long brandId = brand.getId();
        //保存中间表
        saveCategoryBrand(categoryIdList, brandId);

    }


    //更新品牌
    @Override
    //开启本地事务
    @Transactional
    public void updateBrand(BrandVo brandVo) {
        //将vo对象转换pojo数据库对象
        Brand brand = brandVo.toEntity(Brand.class);
        //根据id更新
        this.updateById(brand);
        //先删除中间表，
        this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", brand.getId()));
        //再保存中间表
        this.saveCategoryBrand(brandVo.getCategoryIds(),brand.getId());
    }


    //根据id删除品牌
    @Override
    //开启本地事务
    @Transactional
    public void deleteBrand(Long id) {
        //删除品牌
        this.removeById(id);
        //删除中间表
        this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", id));
    }


    /**
     * 抽取保存中间表方法
     * @param categoryIdList
     * @param brandId
     */
    private void saveCategoryBrand(List<Long> categoryIdList, Long brandId) {
        //获取品牌所属的商品分类id数组,并构造出CategoryBrand对象
        List<CategoryBrand> categoryBrandList = categoryIdList
                .stream()
                .map(cid -> CategoryBrand.of(cid, brandId))
                .collect(Collectors.toList());

        //保存到中间表
        //saveBatch保存一堆对象到数据库
        this.categoryBrandService.saveBatch(categoryBrandList);
    }

}
